﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Honestysoft.Baseframework.WebUI;
using System.Data;
using Honestysoft.BaseObject;
using Honestysoft.Financing.Model;
using Honestysoft.BaseLibrary.ExceptionHandling;
using System.Text;
using Honestysoft.Workflow.BusinessFacade;
using System.Data.Common;

namespace Honestysoft.Financing.WebUI.Module.Audit
{
    public partial class BatchInfo : BasePage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                BindControl();
                Bind();
                BindContract();
            }
        }

        private void BindControl()
        {
            ControlHelper.BindEnum(ddlBatchStatus, typeof(EnumItem.BatchStatus));//此处最好改成typeof(EnumItem.XXX)
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            WFButtons1.AfterCall += new WorkFlow_Control_WFButtons.AfterCallEventHandler(WFButtons1_AfterCall);
            btnSend.Click += new EventHandler(btnSend_Click);
            btnRecall.Click += new EventHandler(btnRecall_Click);
        }

        void btnRecall_Click(object sender, EventArgs e)
        {
            BindContract();
        }

        void btnSend_Click(object sender, EventArgs e)
        {
            BindContract();
        }

        void WFButtons1_AfterCall(Workflow.Model.WFReturn pWFReturn)
        {
            //Bind();
            Response.Redirect("BatchInfo.aspx?ID=" + Request.QueryString["ID"] + "&FunctionID=" + FunctionID);
        }

        private void Bind()
        {
            btnImportRec.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = true;
            btnSend.Enabled = true;

            WFButtons1.BillCode = ((int)EnumItem.WFBill.Batch).ToString();
            WFButtons1.EmployeeID = UserLoginer.LoginUser.ID;
            WFButtons1.BuDataID = Request.QueryString["ID"];
            WFButtons1.IsCallBackPage = true;
            WFButtons1.BeforeTransactJsFuncName = "checkHasRec";

            Bu_AuditBatch obj = new BaseBusinessLogic<Bu_AuditBatch>().GetEntity(Request.QueryString["ID"]);

            if (obj.BatchStatus == ((int)EnumItem.BatchStatus.Lock).ToString())
            {
                hidIsCanOuput.Value = new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).CheckCanOutPutBatch(Request.QueryString["ID"]).ToString();
                WFButtons1.BeforeTransactJsFuncName = "checkCanOutPut";
            }
            numBatchNo.Text = obj.BatchNo.ToString();
            dtpPStartDate.Text = (obj.PStartDate.HasValue ? obj.PStartDate.Value.ToString("yyyy-MM-dd") : "");
            dtpPEndDate.Text = (obj.PEndDate.HasValue ? obj.PEndDate.Value.ToString("yyyy-MM-dd") : "");
            dtpStartDate.Text = (obj.StartDate.HasValue ? obj.StartDate.Value.ToString("yyyy-MM-dd") : "");
            dtpEndDate.Text = (obj.EndDate.HasValue ? obj.EndDate.Value.ToString("yyyy-MM-dd") : "");
            txtRemark.Text = obj.Remark;
            txtCreator.Text = new BaseBusinessLogic<Honestysoft.Baseframework.Model.Sys_User>(Globals.CurrentConnStringName).GetEntity(obj.Creator).UserName;
            hidCreator.Value = obj.Creator;
            dtpCreateTime.Text = obj.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
            ddlBatchStatus.SelectedValue = obj.BatchStatus;

            lblStatus.Text = Honestysoft.EnumHelper.EnumInstance.GetEnumDataText(typeof(EnumItem.BatchStatus), obj.BatchStatus);

            switch ((EnumItem.BatchStatus)int.Parse(ddlBatchStatus.SelectedValue))
            {
                case EnumItem.BatchStatus.Active:
                    WFButtons1.IsHiddenBtnRecall = true;
                    break;
                case EnumItem.BatchStatus.Lock:
                    LockPage();
                    break;
                case EnumItem.BatchStatus.Output:
                    LockPage();
                    dtpEndDate.Enabled = false;
                    dtpPEndDate.Enabled = false;
                    dtpPStartDate.Enabled = false;
                    dtpStartDate.Enabled = false;
                    txtRemark.Enabled = false;
                    break;
                default:
                    break;
            }
            WFButtons1.BindWFControl();
            if (obj.BatchStatus == ((int)EnumItem.BatchStatus.Output).ToString())
            {
                lblInfo.Text = "当前批次已经输出，不能进行任何操作！";
                LockPage();
            }
            else
            {
                WFApply.Tracker ITracker = new WFApply.Tracker(Globals.CurrentConnStringName);
                if (!ITracker.IsCanTransact(UserLoginer.LoginUser.ID, ((int)EnumItem.WFBill.Batch).ToString(), Request.QueryString["ID"]))
                {
                    lblInfo.Text = "对不起，您不是当前批次的流程处理者，不能进行任何操作！";
                    LockPage();
                }
            }

            if (UserLoginer.LoginUser.IsAdmin || (UserLoginer.LoginUser.Roles != null && UserLoginer.LoginUser.Roles.Contains("Administrators")))
            {
                dtpEndDate.Enabled = true;
                dtpPEndDate.Enabled = true;
                dtpPStartDate.Enabled = true;
                dtpStartDate.Enabled = true;
                txtRemark.Enabled = true;
                btnSave.Enabled = true;
            }
        }

        private void LockPage()
        {
            btnImportRec.Enabled = false;
            btnDelete.Enabled = false;
            btnSave.Enabled = false;
            btnSend.Enabled = false;
            
        }

        protected string GetCheckBox(string dataId,string tableId,bool isReceive)
        {
            if (ddlBatchStatus.SelectedValue == ((int)EnumItem.BatchStatus.Lock).ToString()
                || ddlBatchStatus.SelectedValue == ((int)EnumItem.BatchStatus.Output).ToString()) { return ""; }
            if (isReceive) { return ""; }
            string url = string.Format("<input type=\"checkbox\" name=\"chkID\" id=\"chk{0}\"  value=\"{0}|{1}\" />", dataId,tableId);
            return url;
        }

        protected string GetLinkControl(string dataId,bool isSend,bool isRec,bool isBack)
        {
            if (ddlBatchStatus.SelectedValue == ((int)EnumItem.BatchStatus.Lock).ToString()
                || ddlBatchStatus.SelectedValue == ((int)EnumItem.BatchStatus.Output).ToString()) { return ""; }
            //状态：已派单，已签收，被退回
            StringBuilder sb = new StringBuilder();
            if (isBack)
            {
                sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">删除</a>", dataId, btnDelete.ClientID);
                sb.Append("&nbsp;&nbsp;");
                sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">重新派单</a>", dataId, btnSend.ClientID);
            }
            else
            {
                if (isSend && !isRec)
                {
                    sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">收回</a>", dataId, btnRecall.ClientID);
                }
                else
                {
                    if (!isSend)
                    {
                        sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">删除</a>", dataId, btnDelete.ClientID);
                        sb.Append("&nbsp;&nbsp;");
                        sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">派单</a>", dataId, btnSend.ClientID);
                    }
                }
            }

            //if (isBack || (isSend && !isRec) || !isSend)//如果被退回
            //{
            //    sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">删除</a>", dataId, btnDelete.ClientID);
            //    sb.Append("&nbsp;&nbsp;");
            //    sb.AppendFormat("<a href=\"#\" onclick=\"document.getElementById('chk{0}').checked=true;document.getElementById('{1}').click();\">{2}派单</a>", dataId, btnSend.ClientID, (isBack ? "重新" : (isSend ? "重新" : "")));
            //}
            return sb.ToString();
        }

        protected string GetToolTips(object drv)
        {
            //状态：已派单，已签收，被退回
            DataRowView theRow = drv as DataRowView;
            StringBuilder sb = new StringBuilder();
            if (Convert.ToBoolean(theRow["IsBack"]))
            {
                sb.AppendFormat("退回来自：{0}\r\n", theRow["ToUserName"]);
                sb.AppendFormat("退回时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["BackTime"]));
                sb.AppendFormat("退回说明：{0}", theRow["BackDescription"]);
            }
            else
            {
                if (Convert.ToBoolean(theRow["IsReceive"]))
                {
                    sb.AppendFormat("签收人：{0}\r\n", theRow["ToUserName"]);
                    sb.AppendFormat("签收时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["RecTime"]));
                    sb.AppendFormat("签收说明：{0}", theRow["RecOpinion"]);
                }
                else
                {
                    if (Convert.ToBoolean(theRow["IsSend"]))
                    {
                        sb.AppendFormat("接收人：{0}\r\n", theRow["ToUserName"]);
                        sb.AppendFormat("派单时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["SendTime"]));
                    }
                }
            }
            return sb.ToString();
        }

        protected string GetStatus(object drv)
        {
            //状态：已派单，已签收，被退回
            DataRowView theRow = drv as DataRowView;
            StringBuilder sb = new StringBuilder();
            string text="";
            sb.Append("<span title='");
            if (Convert.ToBoolean(theRow["IsBack"]))
            {
                text = "被退回";
                sb.AppendFormat("退回来自：{0}\r\n", theRow["ToUserName"]);
                sb.AppendFormat("退回时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["BackTime"]));
                sb.AppendFormat("退回说明：{0}", theRow["BackDescription"]);
            }
            else
            {
                if (Convert.ToBoolean(theRow["IsReceive"]))
                {
                    text = "已签收";
                    sb.AppendFormat("签收人：{0}\r\n", theRow["ToUserName"]);
                    sb.AppendFormat("签收时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["RecTime"]));
                    sb.AppendFormat("签收说明：{0}", theRow["RecOpinion"]);
                }
                else
                {
                    if (Convert.ToBoolean(theRow["IsSend"]))
                    {
                        text = "已派单";
                        sb.AppendFormat("接收人：{0}\r\n", theRow["ToUserName"]);
                        sb.AppendFormat("派单时间：{0}\r\n", string.Format("{0:yyyy-MM-dd HH:mm:ss}", theRow["SendTime"]));
                    }
                    else
                    {
                        text = "未派单";
                    }
                }
            }
            sb.AppendFormat("'>{0}",text);
            sb.Append("</span>");
            return sb.ToString();
        }

        private void BindContract()
        {
            DataTable dt = new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).GetDocReceiveByBatchID(Request.QueryString["ID"]);
            rptBatchContract.DataSource = dt;
            rptBatchContract.DataBind();
            hidIsHasRec.Value = dt.Rows.Count.ToString();
            int count = 0;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (!Convert.ToBoolean(dr["IsSend"]))
                    {
                        count++;
                    }
                }
            }
            hisIsHasNoSend.Value = count.ToString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Bu_AuditBatch obj = GetSubmitObject();
                new BaseBusinessLogic<Bu_AuditBatch>(Globals.CurrentConnStringName).UpdateEntity(obj);
                //bool ret = new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).UpdateBatch(obj);
                //if (ret)
                //{
                    ScriptHelper.Window.Alert("保存成功！");
                //}
                //else
                //{
                //    ScriptHelper.Window.Alert("保存失败！");
                //}
            }
            catch (BaseException bex)
            {
                ExceptionHelper.ExceptionDistribute(bex, false);
                ScriptHelper.Window.Alert(bex.Message);
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("保存失败！系统发生了未知错误！");
            }
        }

        /// <summary>
        /// 得到提交对象
        /// </summary>
        /// <returns></returns>
        private Bu_AuditBatch GetSubmitObject()
        {
            Bu_AuditBatch obj = new Bu_AuditBatch();
            obj.ID = Request.QueryString["ID"];
            if (numBatchNo.Text.Trim().Length > 0) { obj.BatchNo = Convert.ToInt32(numBatchNo.Text); }
            if (dtpPStartDate.Text.Trim().Length > 0) { obj.PStartDate = Convert.ToDateTime(dtpPStartDate.Text); }
            if (dtpPEndDate.Text.Trim().Length > 0) { obj.PEndDate = Convert.ToDateTime(dtpPEndDate.Text); }
            if (dtpStartDate.Text.Trim().Length > 0) { obj.StartDate = Convert.ToDateTime(dtpStartDate.Text); }
            if (dtpEndDate.Text.Trim().Length > 0) { obj.EndDate = Convert.ToDateTime(dtpEndDate.Text); }
            obj.Remark = txtRemark.Text;
            obj.Creator = hidCreator.Value;// txtCreator.Text;
            //obj.CloseUser = txtCloseUser.Text;
            if (dtpCreateTime.Text.Trim().Length > 0) { obj.CreateTime = Convert.ToDateTime(dtpCreateTime.Text); }
            obj.BatchStatus = ddlBatchStatus.SelectedValue;
            return obj;
        }

        /// <summary>
        /// 得到选中的记录ID集合
        /// </summary>
        /// <returns></returns>
        private string[] GetSelectedRowKeys()
        {
            string strId = Request["chkID"] + "";
            if (string.IsNullOrEmpty(strId)) { return null; }
            return strId.Split(',');
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(Globals.CurrentConnStringName);
            DbConnection connection = transaction.Connection;
            try
            {
                string[] arrId = GetSelectedRowKeys();
                List<string> newArrID = new List<string>();
                List<string> newTableID = new List<string>();
                foreach (string s in arrId)
                {
                    newArrID.Add(s.Split('|')[0]);
                    newTableID.Add(s.Split('|')[1]);
                }
                //BaseBusinessLogic<Bu_BatchRec> baseLogic = new BaseBusinessLogic<Bu_BatchRec>();
                //baseLogic.DeleteByKey(arrId);
                new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).DeleteBatchRec(Request.QueryString["ID"], newArrID.ToArray(), transaction);
                new Honestysoft.Workflow.BusinessFacade.WFApply.FlowManage(Globals.CurrentConnStringName).DeleteWorkflow(((int)EnumItem.WFBill.AuditTable).ToString(), newTableID, transaction);
                transaction.Commit();
                ScriptHelper.Window.Alert("删除成功！");
                BindContract();
            }
            catch (Honestysoft.BaseLibrary.ExceptionHandling.BaseException bex)
            {
                transaction.Rollback();
                ExceptionHelper.ExceptionDistribute(bex, false);
                ScriptHelper.Window.Alert(bex.Message);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                ExceptionHelper.ExceptionDistribute(ex, false);
                ScriptHelper.Window.Alert("删除失败！" + ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }

        protected void btnImportRec_Click(object sender, EventArgs e)
        {
            BindContract();
        }
    }
}